using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Documents;
using System.Linq;

namespace PatentAssistant.Utils
{
    public static class TextUtils
    {
        /// <summary>
        /// 从FlowDocument获取纯文本
        /// </summary>
        public static string GetText(FlowDocument doc)
        {
            if (doc == null) return string.Empty;
            return new TextRange(doc.ContentStart, doc.ContentEnd).Text;
        }

        /// <summary>
        /// 设置FlowDocument的文本内容
        /// </summary>
        public static void SetText(FlowDocument doc, string text)
        {
            if (doc == null) return;
            doc.Blocks.Clear();
            doc.Blocks.Add(new Paragraph(new Run(text)));
        }

        /// <summary>
        /// 追加文本到FlowDocument
        /// </summary>
        public static void AppendText(FlowDocument doc, string text)
        {
            if (doc == null) return;
            doc.Blocks.Add(new Paragraph(new Run(text)));
        }

        /// <summary>
        /// 分割文本为句子
        /// </summary>
        public static List<string> SplitSentences(string text)
        {
            if (string.IsNullOrEmpty(text)) return new List<string>();
            
            // 中文分句规则：按句号、问号、感叹号分割
            var sentences = Regex.Split(text, @"(?<=[。！？.!?])")
                .Where(s => !string.IsNullOrWhiteSpace(s))
                .ToList();
            
            // 处理可能的空句子
            return sentences.Count > 0 ? sentences : new List<string> { text };
        }

        /// <summary>
        /// 移除思维链内容 - 格式为 [CHAIN]...[/CHAIN]
        /// </summary>
        public static string RemoveChainContent(string input)
        {
            if (string.IsNullOrEmpty(input)) return string.Empty;
            
            string result = input;
            
            // 移除 [CHAIN]...[/CHAIN] 格式的内容
            result = Regex.Replace(result, @"\[CHAIN\](.*?)\[/CHAIN\]", "", RegexOptions.Singleline);
            
            // 移除 <think>...</think> 格式的内容
            result = Regex.Replace(result, @"<think>(.*?)</think>", "", RegexOptions.Singleline);
            
            // 移除其他可能的思维链标记
            result = Regex.Replace(result, @"思考过程[：:](.*?)(?=\n\n|\n[A-Z\u4e00-\u9fa5]|$)", "", RegexOptions.Singleline);
            result = Regex.Replace(result, @"分析[：:](.*?)(?=\n\n|\n[A-Z\u4e00-\u9fa5]|$)", "", RegexOptions.Singleline);
            
            // 清理多余的空行
            result = Regex.Replace(result, @"\n{3,}", "\n\n");
            
            return result.Trim();
        }

        /// <summary>
        /// 格式规整
        /// </summary>
        public static string FormatText(string input)
        {
            if (string.IsNullOrEmpty(input)) return string.Empty;
            
            string result = input;
            
            // 1. 统一标点符号
            result = Regex.Replace(result, @"，", "，");
            result = Regex.Replace(result, @"。", "。");
            result = Regex.Replace(result, @"；", "；");
            result = Regex.Replace(result, @"：", "：");
            result = Regex.Replace(result, @"！", "！");
            result = Regex.Replace(result, @"？", "？");
            
            // 2. 规范化空格
            result = Regex.Replace(result, @"\s+", " "); // 多个空格变一个
            result = Regex.Replace(result, @" +(?=[，。；：！？])", ""); // 删除标点前的空格
            
            // 3. 智能排版：规范化段落间距
            result = Regex.Replace(result, @"\n{3,}", "\n\n"); // 多个换行变两个
            result = Regex.Replace(result, @"\n{2,}", "\n\n"); // 确保段落间有适当间距
            
            // 4. 中英文之间加空格
            result = Regex.Replace(result, @"(?<=[a-zA-Z])(?=[\u4e00-\u9fa5])", " ");
            result = Regex.Replace(result, @"(?<=[\u4e00-\u9fa5])(?=[a-zA-Z])", " ");
            
            // 5. 专利交底书标题格式化
            var titlePatterns = new[]
            {
                @"技术领域",
                @"背景技术", 
                @"发明内容",
                @"技术方案",
                @"有益效果",
                @"附图说明",
                @"具体实施方式"
            };
            
            foreach (var pattern in titlePatterns)
            {
                // 确保标题前后有适当的空行，不使用任何特殊符号
                result = Regex.Replace(result, $@"(\n*)(\s*)({pattern})(\s*)(\n*)", $"\n\n{pattern}\n");
            }
            
            // 6. 智能排版：优化段落结构
            // 确保标题后有内容段落
            result = Regex.Replace(result, @"(\n\n[^\n]+\n)(\n{2,})", "$1\n");
            
            // 7. 清理多余的空行，保持整洁
            result = Regex.Replace(result, @"\n{4,}", "\n\n");
            
            // 8. 确保文档开头和结尾的格式
            result = result.Trim();
            if (!result.StartsWith("\n\n"))
            {
                result = "\n\n" + result;
            }
            
            return result;
        }

        /// <summary>
        /// 从文本中提取思维链内容
        /// </summary>
        public static string ExtractChainContent(string input)
        {
            if (string.IsNullOrEmpty(input)) return string.Empty;
            
            var matches = Regex.Matches(input, @"\[CHAIN\](.*?)\[/CHAIN\]", RegexOptions.Singleline);
            if (matches.Count == 0) return string.Empty;
            
            return string.Join("\n\n", matches.Cast<Match>().Select(m => m.Groups[1].Value.Trim()));
        }
    }
} 